<?php

namespace app\admin\controller;

use app\common\controller\Base;
use think\Request;

class Rule extends Base
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        $count = db('rule')->count();
        $data = db('rule')->select();
        $data = get_tree($data);
        $this->assign('data', $data);
        $this->assign('count', $count);
        return view();
    }
    /**
     * 显示创建资源表单页.
     */
    public function create()
    {
        $id = input('get.id/d', '');
        $this->assign('id', $id);
        return view();
    }

    /**
     * 显示编辑资源表单页.
     */
    public function edit()
    {
        $id = input('get.id/d',0);
        $data = db('rule')->field('title,name,status,pid')->where('id',$id)->find();
        $this->assign('id', $id);
        $this->assign('data', $data);
        return view();
    }

    /**
     * 保存新建的资源
     */
    public function save()
    {
        if(request()->isPost()){
            $data['id'] = input('post.id/d','');
            $data['title'] = input('post.title/s','','/([\x{4e00}-\x{9fa5}]+)/u');
            $data['title'] || jump_page('','规则名称必须是汉字!',2);
            $info = db('rule')->where('id','NOT IN',$data['id'])->where('title', $data['title'])->find();
            $info && jump_page('','该规则名称已存在!',2);
            $data['name'] = input('post.name/s','','/\//');
            $data['name'] || jump_page('','规则错误!',2);
            $data['pid'] = input('post.pid/d',0);
            $data['status'] = input('post.status/d',1);
            $data['type'] = input('post.type/d',1);
            $data['conditions'] = input('post.conditions/d',1);
            if($data['id']){
                $id = array_shift($data);
                (db('rule')->where('id', $id)->update($data)) !== false ?  _layer_msg('已更新!','',1) : jump_page('','更新失败!',2);
            }else{
                db('rule')->where('title',$data['title'])->find() &&  _layer_msg('该权限已存在!','admin/rule/create');
                db('rule')->insert($data) ? _layer_msg('已添加!','',1) : _layer_msg('添加失败!','admin/rule/create');
            }
        }
    }

    /**
     * 状态操作
     */
    public function status()
    {
        $id = input('post.id', '');
        $status = input('post.status', '');
        return ($status ? db('rule')->where('id', $id)->update(['status' => '0']) : db('rule')->where('id', $id)->update(['status' => '1'])) ? json(['status'=>1]) : json(['status'=>0,'msg'=>'更新状态失败!']);
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        $ids = rtrim(input('post.id',''), ',');
        if(!$ids) return json(['status'=>0,'msg'=>'请选择要删除的权限!']);
        $data = db('rule')->where('pid','IN',$ids)->find();
        if($data) return json(['status'=>0,'msg'=>'请先删除该节点的子权限!']);
        return db('rule')->delete($ids) ? json(['status'=>1,'msg'=>'已删除!']) : json(['status'=>0,'msg'=>'删除失败!']);
    }
}
